#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , reader_ok(false)
    , show_edge(false)
    , show_bin(false)
    , threshold(100)
{
    ui->setupUi(this);

    reader = new Reader(0);

    if (reader->start()) {
        reader_ok = true;
        ui->statusBar->showMessage(tr("Camera device 0 opened"));
    } else
        ui->statusBar->showMessage(tr("Can't open camera device 0!"));

    connect(reader, &Reader::updateImage, this, &MainWindow::imageUpdate);
}

MainWindow::~MainWindow()
{
    reader->stop();
    reader->quit();
    reader->wait();

    delete ui;
}

void MainWindow::imageUpdate(Mat* img_in)
{
    if (reader_ok) {
        img = img_in->clone();
        if (!img.empty()) {
            if (show_edge) {
                edge_detection(img, img_show);
            } else if (show_bin) {
                image_binary(img, img_show);
            } else {
                img_show = img;
            }
            on_image_show(img_show);
        }
    }
}

void MainWindow::on_pushButton_snapshot_clicked()
{
    if (reader_ok) {
        if (!img.empty()) {
            imwrite("snapshot.png", img);
            ui->statusBar->showMessage(tr("A snapshot saved in ./snapshot.png"), 5000);
        }
    }
}

void MainWindow::on_pushButton_edge_clicked(bool checked)
{
    show_edge = checked;

    if (!show_edge)
        ui->statusBar->showMessage(tr("Extract image edges ..."));
    else
        ui->statusBar->showMessage(tr("Normal mode"));
}

void MainWindow::on_pushButton_bin_clicked(bool checked)
{
    show_bin = checked;

    if (!show_bin)
        ui->statusBar->showMessage(tr("Show binary image ..."));
    else
        ui->statusBar->showMessage(tr("Normal mode"));
}

void MainWindow::on_horizontalSlider_valueChanged(int value)
{
    threshold = value;

    ui->statusBar->showMessage(tr("Threshold: %1").arg(threshold));
}

void MainWindow::on_image_show(Mat& img)
{
    cv::cvtColor(img, img, COLOR_BGRA2RGBA);

    QImage qimg;
    qimg = QImage((const uchar*)(img.data),
        img.cols, img.rows,
        img.cols * img.channels(),
        QImage::Format_RGBA8888);

    QPixmap qpixmap = QPixmap::fromImage(qimg);

    ui->label->setPixmap(qpixmap);
    ui->label->show();
}

void MainWindow::edge_detection(Mat& img_in, Mat& img_out)
{
    // TODO: finish this function
    img_out = img_in;
}

void MainWindow::image_binary(Mat& img_in, Mat& img_out)
{
    // example function
    Mat img_gray;
    cvtColor(img_in, img_gray, COLOR_BGR2GRAY);

    img_gray = img_gray < threshold;

    cvtColor(img_gray, img_out, COLOR_GRAY2BGRA);
}
